package com.gzbd.login.jwt;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.gzbd.login.config.AuthConfig;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * token管理器
 *
 * @author :ys
 * @date :2023-07-27 17:42
 */

@Component
public class CustomTokenManager {
    private final Cache<String, String> tokenCache;



    public CustomTokenManager(AuthConfig authConfig) {
        tokenCache = Caffeine.newBuilder()
                .maximumSize(10000)
                .expireAfterWrite(authConfig.getExpiration(), TimeUnit.SECONDS)
                .build();
    }

    /**
     * 缓存token
     *
     * @param token  用户token, key
     * @param userId 用户ID, value
     */
    public void addToken(String token, String userId) {
        tokenCache.put(token, ObjectUtils.isEmpty(userId) ? "unknown" : userId);
    }

    /**
     * 删除token缓存
     *
     * @param token cache key
     */
    public void removeToken(String token) {
        tokenCache.invalidate(token);
    }

    /**
     * 缓存是否失效
     *
     * @param token cache key
     * @return true: 失效 false: 生效
     */
    public boolean absent(String token) {
        return ObjectUtils.isEmpty(tokenCache.getIfPresent(token));
    }

    /**
     * token 校验
     *
     * @param request HttpServletRequest 获取请求数据
     * @return 校验结果 true:通过 false:不通过
     */
    public boolean checkToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        //登录不校验session
        if (request.getRequestURI().contains("login")) {
            return true;
        }
        if (ObjectUtils.isEmpty(token)) {
            return false;
        }
        return !absent(token);
    }
}
